<template>
    <div class="bookwrap">
          <van-form class="vansForm" @submit="onSubmit"> 
              <br> <br> <br>
            <van-cell-group title="录入人员与客户">
                <van-field
                v-model="username"
                name="name"
                label="用户姓名"
                placeholder="姓名"
                :rules="[{ required: true, message: '请填写姓名' }]"
                />
                <van-field
                v-model="section"
                name="user_phone"
                label="用户电话"
                placeholder="用户电话号码"
                :rules="[{ required: true, message: '请填写用户电话号码' }]"
                />
                <van-field
                    v-model="department"
                    name="type"
                    label="办理业务"
                    placeholder="办理业务"
                    :rules="[{ required: true, message: '请填写办理业务' }]"
                />
            </van-cell-group> 
                <van-field
                    v-model="end_date_result"
                    is-link
                    readonly
                    name="end_date_result"
                    label="办理时间"
                    placeholder="办理时间"
                    @click="showEndCalendar = true"
                    />
                <van-calendar v-model:show="showEndCalendar" @confirm="onEndConfirm" :show-confirm="false" />
            <div style="margin: 24px;margin-bottom: -15px;">
                <van-button :disabled="isRest"  round block type="warning" native-type="submit">
                 {{ isRest?'正在同步...':'提交录入' }}
                </van-button>
                <br>
            </div>
        </van-form>
        <van-divider><b v-if="qr_show" style="font-size:19px;">方式一 抽奖二维码</b></van-divider>
            <qrcode-vue style="position:relative;left:140px;margin-bottom:22px;" v-if="qr_show" :value="qr_value" :size="qr_size" level="H" />
            <van-button type="success" v-if="qr_show" size="small" @click="road2Lucky"> 方式二 前往抽奖 </van-button>   
            <!-- <van-button type="primary" v-if="qr_show" size="small" @click="road2Grid"> 九宫格 </van-button> -->
        <van-divider><b style="font-size:19px;">提交记录</b></van-divider>
        <!-- confirmList -->         
            <div class="confirmWrap">
                <ul class="confirmListItem" v-for="item in confirmList" :key="item.name">
                    <li> <span class="confirmListTitle" > 用户姓名 </span> {{ item.name }} </li>
                    <li> <span class="confirmListTitle"> 办理业务 </span> {{ item.type }} </li>
                    <li> <span class="confirmListTitle"> 办理时间 </span> {{ item.date }} </li>
                    <li> <span class="confirmListTitle"> 用户电话 </span> {{ item.user_phone }} </li>
                    <li class=""> <span class="confirmListTitle"> 用户状态 </span>
                    <span class="confirmListTitleST"> {{ userStatusDict[item.status] }}  </span> </li>
                    <li> <span class="confirmListTitle"> 用户奖品 </span> {{ item.gifts }} </li>
                    <!-- <li class="codeArea"> 1 </li> -->
                </ul>                
            </div> 
        <div class="userInfo">             
            <div class="infoUserText">
                <van-icon name="user-circle-o" /> {{ userInfo }} 
            </div>
        <van-popover v-if="userInfo"  v-model:show="showPopover" :actions="pover_actions" @select="onSelect">
            <template #reference>
                <van-button class="logout" type="primary" plain  size="mini" >登出</van-button>
            </template>
        </van-popover>
             <!-- <div  @click="logout2Main">   登出  </div>    -->
        </div>
     
    </div>
</template>

<script>
    import { ref, getCurrentInstance, computed, onMounted } from 'vue'
    import { useStore } from 'vuex'
    import {useRouter} from 'vue-router'
    import { Toast } from 'vant';
    import utils from "../router/util";
    import QrcodeVue from 'qrcode.vue'


    export default {
        components: { QrcodeVue },
        setup () {
            const router = useRouter();
            const { getters, dispatch } = useStore()
            const isRest = ref(false)
            const username = ref('');
            const password = ref('');
            const department = ref('')
            const section = ref('')
            const telphone = ref('')
            //二维码部分
            const qr_value = ref('1')
            const qr_size = ref(100)
            const qr_show = ref(false)
            const phonePattern = /^1(3|4|5|6|7|8|9)\d{9}$/
            const customer = ref('')
            const space_name = ref('')
            const ad_channel = ref('')
            const ad_type = ref('')
            const ad_duration = ref('')
            const start_date_result = ref(''); // 日历开始
            const end_date_result = ref(''); //日历结束
            const showStartCalendar = ref(false); // 时间戳数据
            const showEndCalendar = ref(false)   // 时间戳数据
            const startCalendarTime = ref('')
            const endCalendarTime = ref('')
            const release_cycle = ref('')
            const release_area = ref('')
            const contract_process = ref('')
            const airflow = ref('')
            const extra_note = ref('')
            let userInfo = ref('')
            let confirmList = ref([])
            const showPopover = ref(false);
            const userStatusDict = ref({
                'nodraw': '未抽奖',
                'draw': '已抽奖，待核销',
                'verty': '已核销'
            })
            // 通过 actions 属性来定义菜单选项
            const pover_actions = [
            { text: '注销当前账号' },          
            { text: '回到首页' },
            ];
            const onSelect = (action) => {
                console.log('action', action)
                if(action.text=='注销当前账号'){
                    utils.clearCookie('user')
                    utils.clearCookie('mytoken')
                    utils.clearCookie('user_type')
                    router.push({
                            name: 'loginSale'
                            })
                    Toast('退出登录')
                }else{
                       router.push({
                            name: 'index'
                            })
                }
            };
            const onStartConfirm = (date) => {
                start_date_result.value = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
                showStartCalendar.value = false;
                startCalendarTime.value = date.getTime() // 时间戳数据
                if(end_date_result.value !== ''){
                    console.log('sss0000000000', endCalendarTime.value)      
                    release_cycle.value = (endCalendarTime.value - date.getTime()) / (1000 * 60 * 60 * 24)+'天'
                    
                }
            };
            const onEndConfirm = (date) => {
                end_date_result.value = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
                showEndCalendar.value = false;
                endCalendarTime.value = date.getTime() // 时间戳数据
                console.log('LLLLLL', date.getTime(), start_date_result.value=='')
                if(start_date_result.value !== ''){
                    console.log('0000000000', startCalendarTime.value)      
                    release_cycle.value = (date.getTime() - startCalendarTime.value) / (1000 * 60 * 60 * 24) + '天'     
                }
            };
            const onSubmit = (values) => {
                console.log('Submit', values, typeof(values), 'user', userInfo.value);
                // 发送 POST 请求 录入新工单***************************
                $axios({
                    method: 'post',
                    url: 'gifts',
                    data: {
                        name: values.name,
                        type: values.type,
                        user_phone: values.user_phone,
                        date: values.end_date_result,
                        confirmer: userInfo.value,
                        gifts: 'default'
                    }
                }).then((res)=>{
                    if(res){
                        console.log('Axios gifts res', res.data)                                   
                        section.value = ''
                        department.value = ''
                        qr_value.value = `http://cloud1-5gc90rkv0c4a396c-1310135976.tcloudbaseapp.com/#/luckyHouse?name=${ username.value }`
                        qr_show.value = true
                        refleshConfirm()
                    }
                }).catch(error=>{
                    console.log('Axios error', error)
                    Toast('重复提交或数据格式不正确')
                } ) 
                Toast('录入成功')
                isRest.value = true
                setTimeout(()=>{
                    isRest.value = false
                }, 5000)
                // const db = $mapp.database();  
                // let status = { record: true, startTime: startCalendarTime.value, endTime: endCalendarTime.value } // 加入一个确定属性，有这个属性的作为有效数据
                // values = Object.assign(values, status)
                // let dbdata =  db.collection("adroom").add(values).then(
                //      (res)=>{  console.log("数据库x成功", res); }
                // )  
            };
            const logout2Main = ()=>{
                showPopover.value = true
                // utils.clearCookie('user')
                // utils.clearCookie('mytoken')
                // utils.clearCookie('user_type')
                // router.push({
                //         name: 'loginSale'
                //         })
            }
            const road2Lucky = ()=>{
                if(!username.value){
                    return
                }
                router.push({
                    name:'luckyHouse',
                    query:{
                        name: username.value
                    }
                })
                  username.value = ''       
            }
            const road2Grid = ()=>{
                if(!username.value){
                    return
                }
                router.push({
                    name:'luckyTiger',
                    query:{
                        name: username.value
                    }
                })
                  username.value = ''       
            }
            
            const refleshConfirm = ()=>{
                $axios({
                    method: 'post',
                    url: `gifts/queryCom/${ userInfo.value }`,      
                }).then((res)=>{
                    if(res){
                        console.log('Axios queryCom res', res.data[0])     
                        confirmList.value = res.data[0]                   
                    }
                }).catch(error=>{
                    console.log('Axios error', error)
                    // Toast('重复提交或数据格式不正确')
                } ) 
            }

            onMounted(async()=>{
                console.log('vuex booking test')
                let res = await dispatch('User/setMainRoute', '/booking')
                userInfo.value = utils.getCookie('user')
                console.log('用户类型', userInfo.value)
                $axios({
                    method: 'post',
                    url: `gifts/queryCom/${ userInfo.value }`,      
                }).then((res)=>{
                    if(res){
                        console.log('Axios queryCom res', res.data[0])     
                        confirmList.value = res.data[0]                   
                    }
                }).catch(error=>{
                    console.log('Axios error', error)
                    // Toast('重复提交或数据格式不正确')
                } ) 
            })
            const currentInstance = getCurrentInstance()
            const { $mapp, $axios } = currentInstance.appContext.config.globalProperties
            return {
                username,
                password,
                onSubmit,
                department,
                section,
                telphone,
                phonePattern,
                customer,
                space_name,
                ad_channel,
                ad_type,
                ad_duration,
                start_date_result,
                end_date_result,
                onStartConfirm,
                onEndConfirm,
                showStartCalendar,
                showEndCalendar,
                release_cycle,
                release_area,
                contract_process,
                airflow,
                extra_note,
                userInfo,
                logout2Main,
                showPopover,
                pover_actions,
                onSelect,
                isRest,
                confirmList,
                road2Lucky,
                qr_value,
                qr_size,
                qr_show,
                road2Grid,
                refleshConfirm,
                userStatusDict
            }
        },
    }
</script>
<style scoped>
.bookwrap{
    text-align: left;
    width: 100%;
    margin-top: -1rem;
    font-size: 20rpx;
}
.vansForm{
    /* margin-left: -0.933333rem !important; */
    width: 100%;
    font-size: 0.3rem ;
    margin-top: 0.9rem;
}
.van-field__value{
    background-color: antiquewhite !important;
}
.userInfo{
    position: absolute;
    top: 5px;
    right: 70px;
}
.logout{
    position: absolute;
    right: -60px;
    top: 3px;
    font-size: 12px;
    line-height: 28px;
    color: darkgoldenrod;
}
.userInfo  .van-button__text{
    font-size: 16px !important;
}
.confirmListItem{
    margin-bottom: 15px;
    background-color: white;
    padding: 6px;
     position: relative;
}
.confirmListItem li {
    font-size: 12px;
    margin-bottom: 5px;
    color: darkcyan;
   
    }
.confirmListTitle{
    font-size: 13px;
    margin-right: 20px;
}
.confirmListTitleST{
    font-size: 16px;
    margin-bottom: 5px;
    color: darkred;
    font-weight: bold;
}
.codeArea{
    position: absolute;
    right: 20px;
    bottom: 46px;
}
</style>